package com.mysteel.rabbitmq;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * MQ的配置
 * @author tannc
 */
public class MqConfig {

    public static  final  String queueName = "tell.all.queue";
    public static  final String exchangeName = "demo.amq.fanout.exchange";
    public static  final String routingKey = "tell.all.route";

    public static Channel initChannel(){

        Connection connection = null;
        Channel channel = null;
        try {
            // 配置连接
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            factory.setPort(5672);
            factory.setUsername("guest");
            factory.setPassword("guest");
            factory.setVirtualHost("/demo");

            // 1.创建与RabbitMQ服务器的TCP连接
            connection = factory.newConnection();
            // 2.创建一个频道
            channel = connection.createChannel();
            // 3.声明交换机类型
            channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT, true);
            // 4.声明默认的队列 (也可不申明队列，使用默认队列)
            channel.queueDeclare(queueName, true, false, true, null);
            // 5.将队列与交换机绑定
            channel.queueBind(queueName, exchangeName, routingKey);
        }catch (Exception e){
            e.printStackTrace();;
        }
        return channel;
    }
}
